<script setup lang="ts">
defineOptions({
  name: "eventConfig"
});
import { ref, reactive, markRaw } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import { queryUserList } from "@/api/modules/fab";
import { userlistPage } from "@/api/checkProject";

interface RuleForm {
  notifyType: string;
  notifyMethods: Array<string>;
  notifyUsersIds: Array<string>;
  notifyUsers: Array<string>;
  notifyNoteCustom: string;
}

interface ListItem {
  value: string;
  label: string;
  [key: string]: any;
}

const eventConfigRuleForm = defineModel({
  type: Object as PropType<RuleForm>,
  default: () => ({
    notifyType: "CONSUME",
    notifyMethods: [],
    notifyUsersIds: [],
    notifyUsers: [],
    notifyNoteCustom: ""
  })
});

const notifyUsersOptions = ref<Array<ListItem>>([]);
const notifyUsersLoading = ref(false);
const eventConfigFormRef = ref<FormInstance | null>(null);
const eventConfigRules = reactive<FormRules<RuleForm>>({
  notifyType: [{ required: true, message: "请选择事件类型", trigger: ["blur", "change"] }],
  notifyMethods: [{ required: true, message: "请选择通知方式", trigger: ["blur"] }],
  notifyUsersIds: [{ required: true, message: "请选择通知人员", trigger: "blur" }],
  notifyNoteCustom: [{ required: false, message: "请输入", trigger: ["blur"] }]
});

const notifyTypeOption = [
  {
    value: "CONSUME",
    label: "用量异常"
  },
  {
    value: "EMISSION",
    label: "排放异常"
  }
];

const notifyMethodsOption = [
  {
    value: "EMAIL",
    label: "邮件通知"
  },
  {
    value: "MESSAGE",
    label: "短信通知"
  }
];

const emits = defineEmits(["change"]);

const clearForm = () => {
  eventConfigRuleForm.value.notifyType = "CONSUME";
  eventConfigRuleForm.value.notifyMethods = [];
  eventConfigRuleForm.value.notifyUsersIds = [];
  eventConfigRuleForm.value.notifyUsers = [];
  eventConfigRuleForm.value.notifyNoteCustom = "";
};

const notifyUsersChangeHandler = () => {
  eventConfigRuleForm.value.notifyUsers = notifyUsersOptions.value
    ?.filter(item => eventConfigRuleForm.value.notifyUsersIds.includes(item.value))
    ?.map(({ value: userId, label: userName }: any) => ({ userId, userName }));
};

const notifyUsersRemoteMethod = async (name: string) => {
  if (name) {
    notifyUsersLoading.value = true;
    const page = 1;
    const pageSize = 9999;
    const usernameLike = name; //  账号查询
    // const realNameLike = realName;  //  姓名查询
    const params = { page, pageSize, usernameLike }; //  账号查询
    // const params = { page, pageSize, realNameLike };  //  姓名查询
    const res = await queryUserList(params);
    const o = res?.data?.map(({ userId: value, username: label }: any) => ({ label, value }));
    notifyUsersOptions.value.unshift(...o);
    notifyUsersOptions.value = notifyUsersOptions.value.filter((item, index, arr) => arr.findIndex(ite => ite.value === item.value) === index);
    notifyUsersLoading.value = false;
  }
};

const validate = (): Promise<Record<string, any>> => {
  return new Promise((resolve, reject) => {
    if (!eventConfigFormRef.value) return reject(false);
    eventConfigFormRef.value.validate(valid => {
      if (valid) {
        resolve(markRaw(eventConfigRuleForm.value));
      } else {
        reject(false);
      }
    });
  });
};

const reset = () => {
  if (!eventConfigFormRef.value) return;
  eventConfigFormRef.value.resetFields();
};

const initNotifyUsersData = (notifyUsers: Array<any>) => {
  if (!notifyUsers?.length) return;
  notifyUsersOptions.value = notifyUsers.map(({ userId: value, userName: label }: any) => ({ label, value }));
  eventConfigRuleForm.value.notifyUsersIds = notifyUsers.map(item => item.userId);
  eventConfigRuleForm.value.notifyUsers = [...notifyUsers];
};

const init = (data: any) => {
  eventConfigFormRef.value.resetFields();
  if (!data?.config) return;
  const {
    config: { notifyType = "", notifyMethods = [], notifyUsers = [], notifyNoteCustom = "" }
  } = data;
  eventConfigRuleForm.value.notifyType = notifyType;
  eventConfigRuleForm.value.notifyMethods = notifyMethods;
  eventConfigRuleForm.value.notifyNoteCustom = notifyNoteCustom;
  initNotifyUsersData(notifyUsers);
};

defineExpose({
  eventConfigFormRef,
  eventConfigRuleForm,
  clearForm,
  validate,
  reset,
  init
});
</script>

<template>
  <px-form
    ref="eventConfigFormRef"
    :model="eventConfigRuleForm"
    :rules="eventConfigRules"
    label-width="120px"
    class="event-config-form"
    scroll-to-error
    status-icon
  >
    <px-row :gutter="24">
      <px-col :span="8">
        <px-form-item label="事件类型" prop="notifyType">
          <px-select v-model="eventConfigRuleForm.notifyType" filterable placeholder="请选择事件类型">
            <px-option v-for="item in notifyTypeOption" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
      </px-col>

      <px-col :span="8">
        <px-form-item label="通知方式" prop="notifyMethods">
          <px-checkbox-group v-model="eventConfigRuleForm.notifyMethods">
            <px-checkbox v-for="item in notifyMethodsOption" :key="item.value" :label="item.value">{{ item.label }}</px-checkbox>
          </px-checkbox-group>
        </px-form-item>
      </px-col>

      <px-col :span="8">
        <px-form-item label="通知人员" prop="notifyUsersIds">
          <px-select
            v-model="eventConfigRuleForm.notifyUsersIds"
            clearable
            multiple
            filterable
            remote
            reserve-keyword
            remote-show-suffix
            collapse-tags
            collapse-tags-tooltip
            placeholder="请选择通知人员"
            :remote-method="notifyUsersRemoteMethod"
            :loading="notifyUsersLoading"
            @change="notifyUsersChangeHandler"
          >
            <px-option v-for="item in notifyUsersOptions" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
      </px-col>

      <px-col :span="24">
        <px-form-item label="通知内容" prop="notifyNoteCustom">
          <px-descriptions :column="2" border>
            <px-descriptions-item label-align="right" label="事件类型">XXXXXXXXX</px-descriptions-item>
            <px-descriptions-item label-align="right" label="事件内容">XXXXXXXXX</px-descriptions-item>
            <px-descriptions-item label-align="right" label="发生时间">XXXXXXXXX</px-descriptions-item>
            <px-descriptions-item label-align="right" label="指标级别">XXXXXXXXX</px-descriptions-item>
            <px-descriptions-item label-align="right" label="机台ID">XXXXXXXXX</px-descriptions-item>
            <px-descriptions-item label-align="right" label="位置">XXXXXXXXX</px-descriptions-item>
            <px-descriptions-item label-align="right" label="机台ower">XXXXXXXXX</px-descriptions-item>
            <px-descriptions-item label-align="right" label="联系方式">XXXXXXXXX</px-descriptions-item>
            <px-descriptions-item label-align="right" label="更多">
              <px-input
                v-model.trim="eventConfigRuleForm.notifyNoteCustom"
                type="textarea"
                clearable
                :rows="1"
                maxlength="1000"
                show-word-limit
                placeholder="请输入"
              />
            </px-descriptions-item>
          </px-descriptions>
        </px-form-item>
      </px-col>
    </px-row>
  </px-form>
</template>

<style lang="scss" scoped>
.event-config-form {
  box-sizing: border-box;
  padding: 16px;
  padding-bottom: 0;

  .px-form-item {
    .px-select,
    .px-input-number,
    .px-descriptions {
      width: 100%;
    }
  }
}
</style>
